package com.rongchuan.wt.service.impl;


import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.rongchuan.wt.constant.MessageContant;
import com.rongchuan.wt.entity.*;
import com.rongchuan.wt.enums.CommonRedisKey;
import com.rongchuan.wt.enums.RankEnum;
import com.rongchuan.wt.mapper.DepartmentMapper;
import com.rongchuan.wt.mapper.EmployeeMapper;
import com.rongchuan.wt.result.PageResult;
import com.rongchuan.wt.service.IEmployeeService;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Random;

@Service
public class EmployeeServiceImpl implements IEmployeeService  {

//    private static final DateTimeFormatter DATE = DateTimeFormatter.ofPattern("yyyy-MM-dd");
    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private DepartmentMapper departmentMapper;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    /**
     * 员工入职
     * @param employeeDTO
     */
    @Override
    public void addEmployee(EmployeeDTO employeeDTO) {
        Employee employee = new Employee();
        BeanUtils.copyProperties(employeeDTO,employee);
        StringBuilder number = new StringBuilder();
        int randomNum = new Random().nextInt(10000); // 0-9999
        String xh = String.format("%04d", randomNum);
        //1、生成员工唯一编号
        LocalDateTime now = LocalDateTime.now();
        number.append(MessageContant.DEPT_CODE).append('-').append(now.getYear()).append('-').append(now.getMonth().getValue()).append('-').append(xh);
        employee.setNumber(number.toString());
        //根据部门名称查询出部门信息的id
        List<Department> select = departmentMapper.select(Department.builder().name(employeeDTO.getDepName()).build());
        if(!CollectionUtils.isEmpty(select)){
            Long  depId = select.get(0).getId();
            employee.setDepId(depId);
        }
        employee.setCreateTime(LocalDateTime.now());
        RankEnum rankEnum = RankEnum.fromCode(employeeDTO.getLevel());
        employee.setLevel(rankEnum.getDescription());
        LocalDateTime entry_time = LocalDate.parse(employeeDTO.getEntryTime()).atStartOfDay();
        employee.setEntryTime(entry_time);
        employeeMapper.insert(employee);
        //2、向缓存插入一条数据
        String employeeKey = CommonRedisKey.EMPLOYEE.getRealKey(String.valueOf(employee.getId()));
        redisTemplate.opsForValue().set(employeeKey, JSON.toJSONString(employee));
        //3、插入成功MQ发送一条异步消息
        EmployeeMessage employeeMessage = new EmployeeMessage();
        employeeMessage.setId(employee.getId());
        employeeMessage.setName(employee.getName());
        rocketMQTemplate.syncSend(MessageContant.EMPLOYEE_INSERT_TOPIC,employeeMessage);
    }

    @Override
    public void deleteEmployee(Long id) {
        //1、先根据人员id查询到该人员
        Employee employee = employeeMapper.selectById(id);
        if(employee != null) {
            //2、修改该人员的状态为离职
            employee.setStatus(MessageContant.YG_STATUS_LZ);
            employeeMapper.updateStatus(employee);

        }
    }

    @Override
    public PageResult pageQuery(EmployeePageQueryDTO employeePageQueryDTO) {
        PageHelper.startPage(employeePageQueryDTO.getPage(),employeePageQueryDTO.getPageSize());
        String leaval = RankEnum.fromCode(employeePageQueryDTO.getLevel()).getDescription();
        Employee employee = new Employee();
//        Long id = departmentMapper.selectByName(employeePageQueryDTO.getDepName());
          //封装查询条件
//        employee.setDepId(employeePageQueryDTO.getDepName()); // 部门
//        employee.setLevel(leaval); // 级别
//        employee.setEntryTime(LocalDate.parse(employeePageQueryDTO.getEntryTime()).atStartOfDay()); // 入职时间

        EmployeePage employeePage = new EmployeePage();
        employeePage.setDep_Name((employeePageQueryDTO.getDepName()));
        employeePage.setLevel(RankEnum.fromCode(employeePageQueryDTO.getLevel()).getDescription());
        employeePage.setEntryBeginTime(employeePageQueryDTO.getEntryBeginTime());
        employeePage.setEntryEndTime(employeePageQueryDTO.getEntryEndTime());
        Page<Employee> page = employeeMapper.pageQuery(employeePage);
        return new PageResult(page.getTotal(), page.getResult());
    }

    /**
     * 导出功能
     * @param response
     */
    @Override
    public void exportBusinessData(HttpServletResponse response) {

        //1 从数据库获取导出的数据
        List<EmployeeExport> list = employeeMapper.exportBusinessData();
        //2 通过POI将数据写入到Excel文件中
        InputStream in = this.getClass().getClassLoader().getResourceAsStream("template/员工数据信息.xlsx");
        try {
            //基于模板文件创建一个新的Excel文件
            XSSFWorkbook excel = new XSSFWorkbook(in);

            //获取表格文件的Sheet页
            XSSFSheet sheet = excel.getSheet("Sheet1");

//            // 表头
//            Row header = sheet.createRow(0);
//            header.createCell(0).setCellValue("姓名");
//            header.createCell(1).setCellValue("工号");
//            header.createCell(2).setCellValue("部门名称");
//            header.createCell(3).setCellValue("职级");

            // 数据
            for (int i = 0; i < list.size(); i++) {
                EmployeeExport employeeExport = list.get(i);
                XSSFRow row = sheet.createRow(i+1);
                row.createCell(0).setCellValue(employeeExport.getName());
                row.createCell(1).setCellValue(employeeExport.getNumber());
                row.createCell(2).setCellValue(employeeExport.getDep_Name());
                row.createCell(3).setCellValue(employeeExport.getLevel());
            }

            //3. 通过输出流将Excel文件下载到客户端浏览器
            ServletOutputStream out = response.getOutputStream();
            excel.write(out);

            //关闭资源
            out.close();
            excel.close();

        }catch (IOException e) {
            e.printStackTrace();
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
